//
//  ；
//  STPhotoBroeser
//
//  Created by StriEver on 16/3/16.
//  Copyright © 2016年 StriEver. All rights reserved.
//

#import "STPhotoBroswer.h"
#import "STImageVIew.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#define MAIN_BOUNDS   [UIScreen mainScreen].bounds
#define Screen_Width  [UIScreen mainScreen].bounds.size.width
#define Screen_Height [UIScreen mainScreen].bounds.size.height
//图片距离左右 间距
#define SpaceWidth    0
@interface STPhotoBroswer ()<STImageViewDelegate,UIScrollViewDelegate>
{
    CGRect _frame;
}
@property (nonatomic, strong) NSArray * imageArray;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) UIScrollView * scrollView;
/**  左边按钮  */
@property (strong, nonatomic) UIButton  *leftButton;
/**  显示label  */
@property (strong, nonatomic) UILabel  *showNumberLabel;

@end
@implementation STPhotoBroswer
- (instancetype)initWithFrame:(CGRect)frame ImageArray:(NSArray *)imageArray currentIndex:(NSInteger)index{
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.imageArray = imageArray;
        self.index = index;
        [self setUpView];
    }
    return self;
}

- (void)clickButton{
    [self dismiss];
}
//--getter

- (UIButton *)leftButton{
    if (!_leftButton) {
        _leftButton = ({
            UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(8, 20, 44, 44)];;
            [button setImage:[UIImage imageNamed:@"nav_icon_back1"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
            button;
            
        });
        
    }
    return _leftButton;
}

- (UILabel *)showNumberLabel{
    if (!_showNumberLabel) {
        _showNumberLabel = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30 * [UIScreen zj_screenWScale], [UIScreen zj_screenHeight] - 70 * [UIScreen zj_screenHScale], 100 , 20 * [UIScreen zj_screenHScale])];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor whiteColor];
            label.backgroundColor = [UIColor clearColor];
            label.font = [UIFont systemFontOfSize:16 * [UIScreen zj_textFontScale]];
            label.text = [NSString stringWithFormat:@"%ld/%lu",self.index + 1,(unsigned long)self.imageArray.count];
            label;
        });
       
    }
    return _showNumberLabel;
}


- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight])];
        _scrollView.backgroundColor = [UIColor blackColor];
        _scrollView.delegate = self;
        //这里
        _scrollView.contentSize = CGSizeMake(Screen_Width * self.imageArray.count, [UIScreen zj_screenHeight]);
        _scrollView.contentOffset = CGPointMake(Screen_Width * self.index, 0);
        _scrollView.scrollEnabled = YES;
        _scrollView.pagingEnabled = YES;
        
        _scrollView.bounces = NO;
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

- (void)setUpView{
    int index = 0;
    if ([self.imageArray[0] isKindOfClass:[NSString class]]) {
        for (NSString *imageString in self.imageArray) {
            STImageVIew * imageView = [[STImageVIew alloc]init];
            imageView.delegate = self;
            __weak typeof(imageView) weakImageView = imageView;
            [MBProgressHUD showHUDAddedTo:imageView animated:YES];
            NSURL *showImageUrl;
            if ([imageString containsString:@"http"]) {
                showImageUrl = [NSURL URLWithString:imageString];
            }else{
                showImageUrl = CREATEURL(imageString);
            }
            [imageView sd_setImageWithURL:showImageUrl
                         placeholderImage:nil
                                  options:SDWebImageCacheMemoryOnly
                                 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                     
                                 }completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                     if (error) {
                                         
                                     }else{
                                         [MBProgressHUD hideHUDForView:weakImageView animated:YES];
                                         
                                     }
                                 }];
            imageView.tag = index;
            
            [self.scrollView addSubview:imageView];
            index ++;
        }
    }else{
        for (NSDictionary *image in self.imageArray) {
            NSArray *keys = [image allKeys];
            STImageVIew * imageView = [[STImageVIew alloc]init];
            imageView.delegate = self;

            if ([keys containsObject:@"image"]) {
                imageView.image = image[@"image"];
            }else{
                [imageView sd_setImageWithURL:CREATEURL(image[@"FILE_PATH"]) placeholderImage:PlaceholderImage];
            }
            [MBProgressHUD showHUDAddedTo:imageView animated:YES];
            imageView.tag = index;
            [self.scrollView addSubview:imageView];
            [MBProgressHUD hideHUDForView:imageView animated:YES];
            index ++;
        }
    }

    [self addSubview:self.leftButton];
     [self addSubview:self.showNumberLabel];
}
#pragma mark ---UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/Screen_Width;
    self.index = index;
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([NSStringFromClass(obj.class) isEqualToString:@"STImageVIew"]) {
            STImageVIew * imageView = (STImageVIew *) obj;
            [imageView resetView];
        }
                }];
    
    if (self.delegate) {
        [self.delegate scrollViewEndScrollViewWithNumber:index];
    }
    
    
    self.showNumberLabel.text = [NSString stringWithFormat:@"%ld/%lu",self.index + 1,(unsigned long)self.imageArray.count];
    
}
- (void)layoutSubviews{
    [super layoutSubviews];
    //主要为了设置每个图片的间距，并且使 图片铺满整个屏幕，实际上就是scrollview每一页的宽度是 屏幕宽度+2*Space  居中。图片左边从每一页的 Space开始，达到间距且居中效果。
    _scrollView.frame = CGRectMake(0, 0, Screen_Width,Screen_Height);
    __weak typeof(self) weakSelf = self;
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.frame = CGRectMake(Screen_Width * idx, 64 + 30 * [UIScreen zj_screenHScale],Screen_Width,weakSelf.height - 120 * [UIScreen zj_screenHScale] - 64);
    }];
    
}
- (void)show{
    self.alpha = 0;
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1;
    }];
    
}
- (void)dismiss{
//    if (self.delegate) {
//        [self.delegate imageViewClick];
//    }
    
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    
   
}
#pragma mark ---STImageViewDelegate
- (void)stImageVIewSingleClick:(STImageVIew *)imageView{
//    [self dismiss];
}
@end
